/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package operator.server;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import share.MessageType;

/**
 *
 * @author mire
 */
public class OperatorLog implements Serializable {

    private final String logName = "transfer.log";
    private final static SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");

    public OperatorLog() {
    }

    public OperatorLog(String fileLog) {
        saveLog(fileLog);
    }

    public synchronized void logTransfer(Date time, int userID, String userNumber, String oldOperatorName) {
        String logLine = dateFormat.format(time) + "\t" + userID + "\t" + userNumber + "\t" + oldOperatorName;
        FileWriter fw = null;
        PrintWriter outp = null;
        try {
            fw = new FileWriter(logName, true);
            outp = new PrintWriter(fw, true);

            outp.println(logLine);

        } catch (IOException ex) {
            Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (outp != null) {
                    outp.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    public synchronized void logMultipleTransfers(Date time, ConcurrentHashMap<Integer, OperatorUser> newUsers, String oldOperatorName) {

        String formatedTime = dateFormat.format(time);
        String logLine = null;
        FileWriter fw = null;
        PrintWriter outp = null;

        try {
            fw = new FileWriter(logName, true);
            outp = new PrintWriter(fw, true);

            for (Iterator<OperatorUser> it = newUsers.values().iterator(); it.hasNext();) {
                OperatorUser u = it.next();
                logLine = formatedTime + "\t" + u.getId() + "\t" + u.getNumber() + "\t" + oldOperatorName;
                outp.println(logLine);
            }

        } catch (IOException ex) {
            Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (outp != null) {
                    outp.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public synchronized String getAllLog() {
        File f = new File(logName);
        if (!f.exists()) {
            return null;
        }

        String returnString = null;
        FileReader fr = null;
        LineNumberReader inr = null;
        String line = null;
        try {
            fr = new FileReader(f);
            inr = new LineNumberReader(fr);

            returnString = "";
            while ((line = inr.readLine()) != null) {
                returnString += line + "\n";
            }

        } catch (IOException ex) {
            Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (inr != null) {
                    inr.close();
                }
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


        return returnString;
    }

    public synchronized String getLast30DaysLog() {
        File f = new File(logName);
        if (!f.exists()) {
            return null;
        }

        String returnString = null;
        FileReader fr = null;
        LineNumberReader inr = null;
        String line = null;
        try {
            fr = new FileReader(f);
            inr = new LineNumberReader(fr);

            returnString = "";
            Calendar cl = getCurrentDateWithoutHours();
            cl.add(Calendar.DATE, -30);
            boolean start = false;
            while ((line = inr.readLine()) != null) {
                if (start) {
                    returnString += line + "\n";
                } else if (parseLogDate(line).after(cl)) {
                    start = true;
                    returnString += line + "\n";
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (inr != null) {
                    inr.close();
                }
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return returnString;

    }

    public static SimpleDateFormat getDateFormat() {
        return dateFormat;
    }

    public static Calendar parseLogDate(String log) {
        String[] splited = log.split("\t");
        Calendar returnDate = Calendar.getInstance();
        try {

            returnDate.setTime(dateFormat.parse(splited[0]));
        } catch (ParseException ex) {
            Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
        }

        return returnDate;
    }

    private Calendar getCurrentDateWithoutHours() {
        Calendar cl = Calendar.getInstance();
        int day = cl.get(Calendar.DAY_OF_MONTH);
        int month = cl.get(Calendar.MONTH);
        int year = cl.get(Calendar.YEAR);
        cl.clear();
        cl.set(year, month, day);
        return cl;
    }

    private void saveLog(String fileLog) {
        File f = new File(logName);
        if (f.exists()) {
            f.delete();
        }

        if(fileLog == null)
            return;

        FileWriter fw = null;
        PrintWriter outp = null;

        try {
            fw = new FileWriter(f, true);
            outp = new PrintWriter(fw, true);

            outp.print(fileLog);

        } catch (IOException ex) {
            Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (outp != null) {
                    outp.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(OperatorLog.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
